package server;

import java.util.ArrayList;
/**
 * ClientSweeper 
 * 1 waits INTERVAL/2 
 * 2 pings all users 
 * 3 waits INTERVAL/2 
 * 4 kicks all clients that has not responded
 * 
 * @author Johannes
 *
 */
public class ClientSweeper implements Runnable {
	private static final int INTERVAL = 5000;
	ArrayList<Client> clients;
	Catalog catalog;
	
	/**
	 * Default constructor
	 * @param catalog catalog reference
	 */
	public ClientSweeper (Catalog catalog){
		this.catalog = catalog;
		this.clients = catalog.clients;
	}
	
	/**
	 * 1 waits INTERVAL/2 
	 * 2 pings all users 
 	 * 3 waits INTERVAL/2 
 	 * 4 kicks all clients that has not responded
	 */
	@Override
	public void run() {
		while(true){
			try {
				Thread.sleep(INTERVAL/2);
				pingClients();
				Thread.sleep(INTERVAL/2);
				kickOutProcedure();
			} catch (InterruptedException e) {}
		}
	}

	
	/**
	 * Pings all clients
	 */
	private void pingClients() {
		synchronized(clients){
			for (int i = 0; i < clients.size(); i++){
				clients.get(i).messageToClient("ping");
				System.out.println(clients.get(i).toString() + " pinged.");
			}
		}
	}
	/**
	 * Removes unresponsive clients
	 */
	private void kickOutProcedure(){
		ArrayList<Client> toBeKicked = new ArrayList<Client>();
		synchronized(clients){
			for (Client client : clients){
				if (client.isPinged()){
					client.unPing();
				} else {
					toBeKicked.add(client);
				}
			}
		}
		for (Client client : toBeKicked){
			catalog.removeClient(client);
		}
	}
}